package com.chujian.system.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chujian.framework.core.base.BaseServiceImpl;
import com.chujian.framework.util.TreeUs;
import com.chujian.sys.entity.SysMenu;
import com.chujian.system.sys.mapper.SysMenuMapper;
import com.chujian.system.sys.service.SysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 菜单表 服务实现类
 *
 * @author chujian
 * @since 2021-08-03
 */
@Service
@Slf4j
public class SysMenuServiceImpl extends BaseServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Override
    public boolean beforeIns(SysMenu paramsData) {
        if (null == paramsData.getMenuPid()) {
            paramsData.setMenuPid(0L);
        }
        return true;
    }

    @Override
    public List<SysMenu> listAllMenuByTemplateId(Long menuTemplateId, boolean includeOper) {
        return this.listAndFull(
                new LambdaQueryWrapper<SysMenu>()
                        .eq(null != menuTemplateId, SysMenu::getMenuTemplateId, menuTemplateId)
                        .le(!includeOper, SysMenu::getMenuType, 2) // 菜单功能
                        .orderByAsc(SysMenu::getOrderNo)
        );
    }

    // TODO cache
    @Override
    public List<SysMenu> listAllRouteMenus(Long menuTemplateId) {
        return this.listAllMenuByTemplateId(menuTemplateId, false);
    }

    @Override
    public List<SysMenu> getTreeMenus(Long menuTemplateId, String menuName) {
        // 按名称查询
        if (StringUtils.isNotEmpty(menuName)) {
            return this.listAndFull(new LambdaQueryWrapper<SysMenu>().like(SysMenu::getMenuName, menuName));
        }

        List<SysMenu> allMenus = this.listAllMenuByTemplateId(menuTemplateId, true);

        return TreeUs.toTree(allMenus, PARENT_MENU_ID, new TreeUs.ITreeCallback<SysMenu>() {
            @Override
            public Serializable getId(SysMenu sysMenu) {
                return sysMenu.getMenuId();
            }

            @Override
            public Serializable getPId(SysMenu sysMenu) {
                return sysMenu.getMenuPid();
            }

            @Override
            public List<SysMenu> getChildren(SysMenu sysMenu) {
                if (null == sysMenu.getChildren()) {
                    sysMenu.setChildren(new ArrayList<>());
                }
                return sysMenu.getChildren();
            }
        });
    }

    @Override
    public Map<Serializable, String> getEchoData(Collection<Serializable> ids) {
        return this.listByIds(ids)
                .stream()
                .collect(Collectors.toMap(SysMenu::getId, SysMenu::getMenuName));
    }
}
